package com.woniuxy.his.common;


import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Properties;
import java.util.Random;

public class CommonUtils {

    public static void sendMail(String reciver,String subject,Object mailMsg) throws MessagingException {
        //通过3个对象将邮件发送出去
        //session   message  transport
        //设置邮件发送的相关环境
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol","SMTP");
        props.setProperty("mail.host","smtp.163.com");
        props.setProperty("mail.smtp.auth","true");
        Authenticator authenticator=new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("swang9798@163.com","DEFEFANLMBPBMLBJ");
            }
        };
        Session session = Session.getInstance(props,authenticator);
        //创建邮件对象，并设置邮件内容
        MimeMessage message = new MimeMessage(session);
        message.setContent(mailMsg,"text/html;charset=utf-8");//设置邮件的内容
        message.setSubject(subject);//设置邮件标题
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(reciver));//设置收件人
        message.setFrom(new InternetAddress("swang9798@163.com"));//设置发件人
        //发送邮件
        Transport.send(message);
    }

    public static String md5(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] digest = md5.digest(password.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(digest);
    }

    public static String getRandomStr( ){
        String source="qwertyuiopasfdghjklzxcvbnm1234567890";
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<4;i++){
            sb.append(source.charAt(new Random().nextInt(source.length())));
        }
        return sb.toString();
    }


}